<?php

namespace app\common\model;

use think\facade\Db;
use think\Model;

class Post extends Model
{
    protected $json = ['media'];
    // 设置JSON数据返回数组
    protected $jsonAssoc = true;

    public function userInfo()
    {
        return $this->hasOne("User", "id", "user_id");
    }

    public function discuss()
    {
        return $this->hasOne("Discuss", "id", "discuss_id");
    }

    public static function getList($where = "", $order = "create_time desc", $paginate = 10, $userId = null)
    {
        $list = self::withJoin(['userInfo'])->where($where)->order($order)->paginate($paginate)->each(function ($item) use ($userId) {

            if ($item["vote_id"]) {
                $vote = Db::name("vote_subject")->where("id", $item["vote_id"])->find();
                $vote["options"] = Db::name("vote_option")->where("vote_id", $vote["id"])->select();
                $item["vote_info"] = $vote;
            }

            //是否点赞
            $item["is_thumb"] = false;
            $isThumb = Db::name("post_thumb")->where(["user_id" => $userId, "post_id" => $item["id"]])->find();

            if ($isThumb) {
                $item["is_thumb"] = true;
            }

            $item["discuss_list"] = json_decode($item["discuss_list"]);
            return $item;
        });
        return $list;
    }
}